/*******************************************************************************
 * Copyright (c) 2009 David Harrison.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl-3.0.html 
 *  
 * Contributors:
 *     David Harrison - initial API and implementation
 ******************************************************************************/
package com.sfs.postcodes.webservice.soap;

import com.sfs.postcodes.beans.GeocodeBean;
import com.sfs.postcodes.dao.GeocoderDAO;
import com.sfs.postcodes.dao.GeocodeLookupException;
import com.sfs.postcodes.dao.PostcodeDAO;
import com.sfs.postcodes.dao.PostcodeLookupException;

import java.io.IOException;


public class PostcodeServiceImpl implements PostcodeService {
        
    private PostcodeDAO postcodeDAO = null;    
    private GeocoderDAO geocoderDAO = null;
    

    //spring 'injects' this implementation
    public void setPostcodeDAO(PostcodeDAO postcodeDAO) {
        this.postcodeDAO = postcodeDAO;
    }
    
    //spring 'injects' this implementation
    public void setGeocoderDAO(GeocoderDAO geocoderDAO) {
        this.geocoderDAO = geocoderDAO;
    }
    
    public String lookup(final String address, final String state, 
            final String country)
    {  
        String postcode = "";
        if(this.postcodeDAO!=null) {
            try {            
                postcode =  postcodeDAO.findPostcode(address, state, country);
            } catch (PostcodeLookupException pe) {
                postcode = "Error looking up postcode: " + pe.getMessage();
            }
        } else {
            postcode = "This service is not configured correctly";
        }
        return postcode;  
    }
    
    public String geocode(final String address, final String state, 
            final String country)
    {     
        String coordinates = "";
        if(this.geocoderDAO!=null) {
            try {
                GeocodeBean geocode = this.geocoderDAO.findGeocode(
                        address, state, country);
                if(geocode!=null) {
                    coordinates = geocode.getCoordinates();
                }
            } catch (GeocodeLookupException ge) {
                coordinates = "Error looking up geocode: " + ge.getMessage();
            } catch (IOException io) {
                coordinates = "Error preparing geocode lookup: " 
                        + io.getMessage();
            }
        } else {
            coordinates = "This service is not configured correctly";
        }
        return coordinates;
    }    
}
